package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.soledroid.Model.Canteen;

class FetchCanteenTask extends AsyncTask<Void, Void, ArrayList<Canteen>> {
	ProgressDialog dialog;
    protected ArrayList<Canteen> doInBackground(Void... params) {
    	ArrayList<Canteen> listItems = new ArrayList<Canteen>();

 		try {
 			URL url = new URL("http://soledroid.huytoan.com/canteen");
 			URLConnection tc = url.openConnection();
 			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

 			String line;
 			while ((line = in.readLine()) != null) {
 				JSONArray ja = new JSONArray(line);

 				for (int i = 0; i < ja.length(); i++) {
 					JSONObject jo = (JSONObject) ja.get(i);
 					Canteen canteen = new Canteen(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
 							jo.getString("description"), jo.getString("latitude"), jo.getString("longitude"), jo.getInt("no_of_stalls"));
 					listItems.add(canteen);
 				}
 			}
 			
 		} catch (Exception e) {
 			e.printStackTrace();
 		} 
 		
 		return listItems;
     }
     
     protected void onPreExecute() {
//    	 dialog = ProgressDialog.show(LoadBrowseActivity.getContext(), "",
//    			 "Please wait for few seconds...", true);
     }
     
     protected void onProgressUpdate(Void... params) {
     }

     protected void onPostExecute(ArrayList<Canteen> result) {
         //show real UI
    	 dialog.dismiss();
     }

 }